package studyguide.ch08;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class LayoutsMidlet extends MIDlet {

	private final Form form;
	private final Command exitCommand;
	private final Display display;
	
	private class SampleCommandListener implements CommandListener {

		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
		
	}
	
	public LayoutsMidlet() throws IOException {
		form = new Form("Layouts Sample");
		
		exitCommand = new Command("Exit", Command.EXIT, 1);
		
		form.addCommand(exitCommand);
		SampleCommandListener listener = new SampleCommandListener();
		form.setCommandListener(listener);
		display = Display.getDisplay(this);
		
		// Assemple form:
		StringItem leftItem = new StringItem("Left:", "left");
		leftItem.setLayout(Item.LAYOUT_LEFT | Item.LAYOUT_TOP | Item.LAYOUT_NEWLINE_AFTER);

		StringItem centerItem = new StringItem("Center:", "center");
		centerItem.setLayout(Item.LAYOUT_CENTER | Item.LAYOUT_VCENTER | Item.LAYOUT_NEWLINE_AFTER);
		
		StringItem rightItem = new StringItem("Right:", "right");
		rightItem.setLayout(Item.LAYOUT_RIGHT | Item.LAYOUT_BOTTOM | Item.LAYOUT_NEWLINE_AFTER);
		
		TextField smallField = new TextField(
				"Field:", "value", 5, TextField.ANY);
		smallField.setLayout(Item.LAYOUT_LEFT);
		// Even only 5 charactes are allowed, field will have 200 pixels
		smallField.setPreferredSize(200, -1);
		
		form.append(leftItem);
		form.append(centerItem);
		form.append(rightItem);
		form.append(smallField);
	}
	
	protected void destroyApp(boolean unconditional) {
		// No Op
	}

	protected void pauseApp() {
		// No Op
	}

	protected void startApp() throws MIDletStateChangeException {
		display.setCurrent(form);
	}

}
